#!/usr/bin/env bash

# create or truncate the file
> /etc/ssl/deis_certs

{{ range $cert := ls "/deis/certs" }}
echo {{ $cert }} >> /etc/ssl/deis_certs
{{ end }}

CERT_PATH=/etc/ssl/deis/certs
KEY_PATH=/etc/ssl/deis/keys

# clean up all certs
rm -rf $CERT_PATH
rm -rf $KEY_PATH

# ...then re-create the paths
mkdir -p $CERT_PATH
mkdir -p $KEY_PATH

{{ if gt (len (lsdir "/deis/certs")) 0 }}
while read etcd_path; do
  {{ range $cert := ls "/deis/certs" }}
  if [[ "$etcd_path" == "{{ $cert }}" ]]; then
    cat << EOF > "$CERT_PATH/$etcd_path.cert"
{{ getv (printf "/deis/certs/%s/cert" $cert) }}
EOF
    cat << EOF > "$KEY_PATH/$etcd_path.key"
{{ getv (printf "/deis/certs/%s/key" $cert) }}
EOF
  fi{{ end }}
done < /etc/ssl/deis_certs
{{ else }}
# there is no certificates to generate
{{ end }}

